package org.example.commond.handler;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.example.commond.AbstractCmdHandler;
import org.example.component.UserInfo;
import org.example.config.Chat;
import org.example.config.Im;
import org.example.config.ImConfig;
import org.example.enums.CommandEnum;
import org.example.packets.bean.*;
import org.example.packets.handler.message.ChatRespBody;
import org.example.packets.handler.system.RespBody;
import org.example.packets.handler.user.GroupUser;
import org.example.packets.handler.user.UserRespBody;
import org.tio.core.ChannelContext;
import org.tio.core.intf.Packet;
import org.tio.websocket.common.WsResponse;

import java.util.List;

@Slf4j
public class UserReqHandler extends AbstractCmdHandler {

    @Override
    public CommandEnum command() {
        return CommandEnum.COMMAND_GET_USER_REQ;
    }

    @Override
    public WsResponse handler(Packet packet, ChannelContext channelContext) {

        User user = UserInfo.user();
        UserRespBody userRespBody = new UserRespBody().setUser(user).setGroups(UserInfo.groups());
        WsResponse response = WsResponse.fromText(RespBody.success(CommandEnum.COMMAND_GET_USER_RESP, userRespBody), ImConfig.CHARSET);
        Im.send(channelContext, response);
//        log.info("单个群组处理耗时:" + timer.intervalRestart());

        // 倒着循环, 解决未读上线的问题
        for (int i = UserInfo.groups().size() - 1; i >= 0; i--) {
            Group group = UserInfo.groups().get(i);

            // 获取到最后一条消息未读消息,并且重新发送
            List<UnReadMessage> unReadMessages = unReadMessageService.getUnReadMessage(user.getId(), group.getRoomId());
            group.setUnreadCount(unReadMessages.size());

            if (CollUtil.isNotEmpty(unReadMessages)) {
                UnReadMessage unReadMessage = unReadMessages.get(unReadMessages.size() - 1);
                Message message = messageService.getMessage(unReadMessage.getMessageId());
                if (null == message){
                     continue;
                }
                ChatRespBody chatRespBody = BeanUtil.copyProperties(message, ChatRespBody.class);
                User userInfo = ImConfig.userListener().onGetUser(chatRespBody.getSenderId());
                chatRespBody.setAvatar(userInfo.getAvatar());
                chatRespBody.setUsername(userInfo.getUsername());
                chatRespBody.setUnreadCount(CollUtil.isEmpty(unReadMessages) ? 0 : unReadMessages.size());
                WsResponse wsResponse = WsResponse.fromText(RespBody.success(CommandEnum.COMMAND_CHAT_REQ, chatRespBody), Im.CHARSET);
                Im.send(channelContext, wsResponse);
            }
        }
        return null;
    }
}
